import cloud from '@lafjs/cloud'
import { createHmac } from "crypto";
let ACCESS_KEY_ID = "6tPvFq415pA7Kd0oaPl5WV6A"
let ACCESS_KEY_SECRET = "FEnW20v8dBExD6UKZ8ki41z87myuAI"
let baseUrl = "https://api.baiwangjs.com/swgx-saas/agentinvoiceservice-cloudservice-cloudservice/agentiscloud"


//百旺开票相关
export async function baiwangInvoice(query) {
  const json_str = JSON.stringify(query.data);
  const request_data = Buffer.from(json_str).toString('base64');//body的入参

  let date_format = new Date().toUTCString() //时间
  let generateRandom = generateRandomId()//随机数
  let host = "api.baiwangjs.com"
  let ua = "Java 1.8.0_181 64 bit, sdk-ver=1.0.0"

  let sign_str = `POST /swgx-saas/agentinvoiceservice-cloudservice-cloudservice/agentiscloud/cloud/${cloud.utils.substringFn(query.url)} HTTP/1.1
date: ${date_format}
host: ${host}
x-htjs-nonce: ${generateRandom}
x-htjs-ua: ${ua}`

  let signature = generateHmacSha256Base64(sign_str)

  let Authorization = `hmac username="${ACCESS_KEY_ID}", algorithm="hmac-sha256", headers="request-line date host x-htjs-nonce x-htjs-ua", signature="${signature}"`

  let request = {
    url: `${baseUrl}${query.url}`,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      Authorization,
      "x-htjs-ua": ua,
      Host: host,
      "x-htjs-nonce": generateRandom,
      Date: date_format,
    },
    body: request_data
  }

  try {
    const response = await fetch(request.url, {
      method: request.method,
      headers: request.headers,
      body: request.body
    })
    const obj = await response.json()
    //console.log("翻译json", obj);


    if (obj.code == 0) { //开票成功
      return obj.hasOwnProperty("data") ? obj.data : obj
    } else if (!obj.hasOwnProperty("code")) {
      return obj
    }
    else {
      return cloud.utils.requestReturn({ msg: obj.renson ? obj.renson : obj.message, code: 500 })
    }
  } catch (error) {
    return cloud.utils.requestReturn({ msg: error.response.data, code: 500 })
  }


  //生成随机数
  function generateRandomId() {
    const randomId = `${Math.random().toString(16).substr(2, 8)}-${Math.random().toString(16).substr(2, 4)}-${Math.random().toString(16).substr(2, 4)}-${Math.random().toString(16).substr(2, 4)}-${Math.random().toString(16).substr(2, 12)}`;
    return randomId;
  }

  //生成sign
  function generateHmacSha256Base64(text: string): string {
    const hmac = createHmac('sha256', ACCESS_KEY_SECRET);
    hmac.update(text);
    return hmac.digest('base64');
  }
}

